from django.contrib import admin

from china_regions.models import Province, City, Country, Town


class CityListFilter(admin.SimpleListFilter):
    title = ('省')

    parameter_name = 'code'

    def lookups(self, request, model_admin):
        return Province.objects.all().values_list('id', 'name')

    def queryset(self, request, queryset):
        if self.value():
            id = request.GET.get('code')
            city = City.objects.filter(province_id=id)
            return city
        else:
            return queryset


class CountryListFilter(admin.SimpleListFilter):
    title = ('选择')
    parameter_name = 'city'

    def lookups(self, request, model_admin):
        name = request.GET.get('city__province__name')
        if name is not None:
            return City.objects.filter(province_id=Province.objects.get(name__icontains=name).id).values_list('id',
                                                                                                              'name')
        else:
            return []

    def queryset(self, request, queryset):
        name = request.GET.get('city__province__name')
        city = request.GET.get('city')
        if name is not None and city is not None:
            if Province.objects.get(name__icontains=name).id == City.objects.get(id=city).province_id:
                return Country.objects.filter(city=city)
        return queryset


class CountryList(admin.SimpleListFilter):
    title = ('选择')
    parameter_name = 'city'

    def lookups(self, request, model_admin):
        name = request.GET.get('country__city__province__name')
        if name is not None:
            return City.objects.filter(province_id=Province.objects.get(name__icontains=name).id).values_list('id',
                                                                                                              'name')
        else:
            return []

    def queryset(self, request, queryset):
        name = request.GET.get('country__city__province__name')
        city = request.GET.get('city')
        if name is not None and city is not None:
            if Province.objects.get(name__icontains=name).id == City.objects.get(id=city).province_id:
                return Country.objects.filter(city=city)
        return queryset


class TownListFilter(admin.SimpleListFilter):
    title = ('选择')
    parameter_name = 'country'

    def lookups(self, request, model_admin):
        city = request.GET.get('city')
        country = request.GET.get('country')
        if city is not None and country is not None:
            return Country.objects.filter(city_id=city).values_list('id', 'name')
        else:
            return []

    def queryset(self, request, queryset):
        country = request.GET.get('country')
        if country is not None:
            if Country.objects.get(id=country).country_id == country:
                return Town.objects.filter(country_id=country)
        return queryset
